/**
 * 
 */
package niuke.wap;

import java.util.LinkedList;
import java.util.Scanner;

/**
 * @author zhongfang
 *
 */
public class test2 {

	static class LinearStructure {
		boolean reverse = false;
		LinkedList<Integer> list = new LinkedList<>();
		LinkedList<Integer> maxRec = new LinkedList<>();
		int maxCount = 0;

		public void reverse() {
			if (!list.isEmpty())
				reverse = !reverse;
		}

		public int pop_back_act() {// 从尾部删除
			if (list.isEmpty()) {
				return -1;
			}
			// 想一下怎么更新max
			maxRec.removeLast();
			return list.removeLast();
		}

		public int pop_front_act() {// 从头部删除
			if (list.isEmpty()) {
				return -1;
			}
			if (maxRec.removeFirst() == max()) {
				maxCount--;
			}
			if (maxCount == 0) {

			}
			return list.removeFirst();
		}

		public int pop_back() {
			if (reverse) {
				return pop_front_act();
			} else {
				return pop_back_act();
			}
		}

		public int pop_front() {
			if (!reverse) {
				return pop_front_act();
			} else {
				return pop_back_act();
			}
		}

		public void push_front(int x) {
			if (!reverse) {
				push_front_act(x);
			} else {
				push_back_act(x);
			}
		}

		public void push_back(int x) {
			if (!reverse) {
				push_back_act(x);
			} else {
				push_front_act(x);
			}
		}

		private void push_back_act(int x) {// 尾部插入
			if (list.isEmpty()) {
				maxRec.add(x);
			} else {
				int oriMax = maxRec.getLast();
				if (oriMax < x) {
					maxRec.addLast(x);
				} else {
					maxRec.addLast(oriMax);
				}
			}
			list.addLast(x);
		}

		private void push_front_act(int x) {// 头部插入
			if (list.isEmpty()) {
				maxRec.add(x);
			} else {
				int oriMax = maxRec.getFirst();
				if (oriMax < x) {
					maxRec.addFirst(x);
				} else {
					maxRec.addFirst(oriMax);
				}
			}
			list.addFirst(x);
		}

		public int max() {
			if (list.isEmpty()) {
				return -1;
			}
			return Math.max(maxRec.getFirst(), maxRec.getLast());
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		scanner.nextLine();
		LinearStructure structure = new LinearStructure();
		for (int i = 0; i < n; i++) {
			String string = scanner.nextLine();
			int res = -2;
			if (string.equals("pop_back")) {
				res = structure.pop_back();
			} else if (string.equals("pop_front")) {
				res = structure.pop_front();
			} else if (string.equals("reverse")) {
				structure.reverse();
			} else if (string.equals("max")) {
				res = structure.max();
			} else {
				String[] strings = string.split(" ");
				int x = Integer.parseInt(strings[1]);
				if (strings[0].equals("push_front")) {
					structure.push_front(x);
				} else {
					structure.push_back(x);
				}
			}
			if (res == -2) {
				continue;
			} else if (res == -1) {
				System.out.println("Error");
			} else {
				System.out.println(res);
			}
		}
	}
}
